package com.sx.micowell.module.login

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.mvvm.bar.OnTitleBarListener
import com.example.mvvm.base.ContainerActivity
import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.rx.RxBus
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import com.miloyu.modelnet.response.TicketVO
import com.sx.micowell.R
import com.sx.micowell.databinding.FragWxScanBinding
import com.sx.micowell.framework.app.AppConstant
import com.sx.micowell.framework.app.IntentKey
import com.sx.micowell.framework.app.MyFragment
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.arouth.RoutePath
import com.sx.micowell.framework.model.LoginModel
import com.sx.micowell.framework.tools.wxapi.WxEntryRespEvent
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.diffdev.DiffDevOAuthFactory
import com.tencent.mm.opensdk.diffdev.IDiffDevOAuth
import com.tencent.mm.opensdk.diffdev.OAuthErrCode
import com.tencent.mm.opensdk.diffdev.OAuthListener

/**
 * @Author: YY
 * @Time: 2021/9/13
 * @Describe 微信二维码登录
 */
@Route(path = RoutePath.WX_QR_CODE_LOGIN)
class WxQRCodeLoginFragment : MyFragment<FragWxScanBinding, ContainerActivity>(),
    OnTitleBarListener {

    lateinit var viewMode: LoginModel

    override fun initViewModel() {
        super.initViewModel()
        viewMode = getFragmentScopeViewModel(LoginModel::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.frag_wx_scan)
    }

    override fun initView() {
        ImmersionBar.with(this).statusBarDarkFont(true)
            .fitsSystemWindows(true).init()
        binding.title.setOnTitleBarListener(this)
    }

    override fun initData() {
        viewMode.getSdkTicket()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewMode.wxQrDataEvent.observe(this, {
            qrAuth(it)
        })
    }

    private fun qrAuth(ticketVO: TicketVO) {
        val iDiffDevOAuth = DiffDevOAuthFactory.getDiffDevOAuth()
        iDiffDevOAuth.auth(
            ticketVO.appid,
            ticketVO.scope,
            ticketVO.noncestr,
            ticketVO.timestamp.toString(),
            ticketVO.signature,
            object : OAuthListener {
                override fun onAuthGotQrcode(s: String?, bytes: ByteArray?) {
                    // TODO: auth之后返回的二维码接口
                    LogUtils.d("onAuthGotQrcode------${s}----------${bytes?.size}")
                    if (bytes != null) {
                        val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                        HANDLER.post { binding.imageQrCode.setImageBitmap(bitmap) }
                    }
                }

                override fun onQrcodeScanned() {
                    // TODO: 用户扫描二维码之后，回调改接口
                    LogUtils.d("onQrcodeScanned")
                }

                override fun onAuthFinish(oAuthErrCode: OAuthErrCode?, s: String?) {
                    // TODO: 用户点击授权后，回调改接口
                    LogUtils.d("onAuthFinish: " + oAuthErrCode!!.code + "--- " + s)
                    when (oAuthErrCode.code) {
                        OAuthErrCode.WechatAuth_Err_OK.code -> {
                            RxBus.getDefault().post(
                                WxEntryRespEvent(ConstantsAPI.COMMAND_SENDAUTH,
                                    OAuthErrCode.WechatAuth_Err_OK.code, s!!, null)
                            )
                            mActivity.finish()
                        }

                        OAuthErrCode.WechatAuth_Err_Cancel.code -> {
                            ToastUtils.showShort("取消授权")
                        }
                    }

                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        DiffDevOAuthFactory.getDiffDevOAuth().detach()
    }

    override fun onLeftClick(view: View?) {
        myActivity.finish()

    }

    override fun onTitleClick(view: View?) {
    }

    override fun onRightClick(view: View?) {
    }
}